//
//  BPAccountSettingViewController.m
//  BabyPhotograph
//
//  Created by cesh on 2017/2/16.
//  Copyright © 2017年 cesh. All rights reserved.
//

#import "BPAccountSettingViewController.h"
#import "UIBarButtonItem+Extensions.h"
#import "BPAddressViewController.h"
#import "WKPicClipViewController.h"
#import <UIImageView+WebCache.h>
@interface BPAccountSettingViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate, PicClipDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *headerImg;
@property (weak, nonatomic) IBOutlet UITextField *nickname;

@property (weak, nonatomic) IBOutlet UILabel *phone;

@property (weak, nonatomic) IBOutlet UIButton *female;
@property (weak, nonatomic) IBOutlet UIButton *male;
@property (weak, nonatomic) IBOutlet UIView *addressView;

@property (strong, nonatomic) NSDictionary *user;

@property (assign, nonatomic) BOOL headerChange;

@end

@implementation BPAccountSettingViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.alpha = 1.0;
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.alpha = 1.0;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"账号设置";
    self.user = [[NSUserDefaults standardUserDefaults]objectForKey:@"user"];
    
    self.headerImg.layer.cornerRadius = 40.0;
    self.headerImg.layer.masksToBounds = YES;
    
    self.nickname.text = self.user[@"nickname"];
    self.phone.text = self.user[@"phone"];
    [self.headerImg sd_setImageWithURL:[NSURL URLWithString:self.user[@"imgs"][0]] placeholderImage:[UIImage imageNamed:@"zhanweitu"]];
    self.headerChange = NO;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveItems)];
    //性别字段：0 未选择 1: 男 2 : 女
    NSString *sex = self.user[@"sex"];
    if ([sex isEqualToString:@"1"]) {
        [self maleClick:_male];
    }
    if ([sex isEqualToString:@"2"]) {
        [self femaleClick:_female];
    }
    
    
    [_addressView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOnAddressView)]];
    //更改头像
    self.headerImg.userInteractionEnabled = YES;
    [self.headerImg addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changeHeader:)]];
}

- (void)changeHeader:(UITapGestureRecognizer *)tap {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *albumPic = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //图片选择控制器
        UIImagePickerController *imagePickerC = [[UIImagePickerController alloc]init];
        //设置进入本地的哪个相册
        imagePickerC.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        //设置代理实现图片的选中
        imagePickerC.delegate = self;
        [self presentViewController:imagePickerC animated:YES completion:nil];
    }];
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //图片选择控制器
        UIImagePickerController *imagePickerC = [[UIImagePickerController alloc]init];
        //设置进入照相机
        imagePickerC.sourceType = UIImagePickerControllerSourceTypeCamera;
        //设置代理实现图片的选中
        imagePickerC.delegate = self;
        [self presentViewController:imagePickerC animated:YES completion:nil];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:albumPic];
    [alert addAction:camera];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}

//UIImagePickerControllerDelegate方法，本地相册和照相机照下来的照片选中后做如下操作
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    //获取选中的图片
    UIImage *selectedImage =  info[UIImagePickerControllerOriginalImage];
    //图片剪裁界面
    WKPicClipViewController *picClipVC = [[WKPicClipViewController alloc]init];
    picClipVC.delegate = self;
    picClipVC.img = selectedImage;
    
    //更改按钮的背景图片
    self.headerImg.image = picClipVC.img;
    self.headerChange = YES;
    //退出图片选择器
    [self dismissViewControllerAnimated:NO completion:nil];
    [self presentViewController:picClipVC animated:NO completion:nil];
}

- (void)picClipViewController:(WKPicClipViewController *)picClipViewController clippedImage:(UIImage *)clippedImage {
    self.headerImg.image = clippedImage;
}

- (void)saveItems {
    if (_female.isSelected == NO && _male.isSelected == NO) {
        [SVProgressHUD showInfoWithStatus:@"请选择性别"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    self.user = [[NSUserDefaults standardUserDefaults]objectForKey:@"user"];
    NSLog(@"%@",self.user);
    //判定哪些item发生了改变
    NSString *newName = self.nickname.text;
    BOOL nameChange = ![newName isEqualToString:self.user[@"nickname"]];
    
    NSString *newSex = _male.isSelected ? @"1" : @"2";
    BOOL sexChange = ![newSex isEqualToString:self.user[@"sex"]];
    
    //根据哪些item发生了改变做相应的操作
    if (nameChange) {
        AFHTTPSessionManager *mgrName = [AFHTTPSessionManager manager];
        mgrName.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/html",
                                                         @"image/jpeg",
                                                         @"image/png",
                                                         @"application/octet-stream",
                                                         @"text/json",
                                                         nil];
        
        [mgrName POST:[NSString stringWithFormat:@"%@?c=User&&a=updateNickname",requestURL]
           parameters:@{@"token" : self.user[@"token"],
                        @"newNickname" : self.nickname.text}
             progress:^(NSProgress * _Nonnull uploadProgress) {
                 
             } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                 if ([responseObject[@"state"] isEqualToString:@"SUCCESS"]) {
                     NSLog(@"昵称更改成功");
                     [[NSUserDefaults standardUserDefaults]setObject:responseObject[@"data"] forKey:@"user"];
                     //将左边用户的昵称更改
                     [[NSNotificationCenter defaultCenter]postNotificationName:@"changeUserNickname" object:responseObject[@"data"][@"nickname"]];
                 }
                 else {
                     NSLog(@"昵称更改失败 %@", responseObject[@"data"]);
                 }
             } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                 NSLog(@"请求失败");
             }];
    }
    
    if (sexChange) {
        AFHTTPSessionManager *mgrSex = [AFHTTPSessionManager manager];
        mgrSex.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                             @"text/html",
                                                             @"image/jpeg",
                                                             @"image/png",
                                                             @"application/octet-stream",
                                                             @"text/json",
                                                             nil];
        
        [mgrSex POST:[NSString stringWithFormat:@"%@?c=User&&a=updateSex",requestURL]
           parameters:@{@"token" : self.user[@"token"],
                        @"sex" : newSex}
             progress:^(NSProgress * _Nonnull uploadProgress) {
                 
             } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                 if ([responseObject[@"state"] isEqualToString:@"SUCCESS"]) {
                     NSLog(@"性别更改成功");
                     [[NSUserDefaults standardUserDefaults]setObject:responseObject[@"data"] forKey:@"user"];
                 }
                 else {
                     NSLog(@"性别更改失败 %@", responseObject[@"data"]);
                 }
             } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                 NSLog(@"请求失败");
             }];
    }
    
    if (self.headerChange) {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        //接收类型不一致请替换一致text/html或别的
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                             @"text/html",
                                                             @"image/jpeg",
                                                             @"image/png",
                                                             @"application/octet-stream",
                                                             @"text/json",
                                                             @"text/plain",
                                                             nil];
        NSDictionary * dict = @{
                                @"token" : self.user[@"token"],
                                };
        [manager POST:[NSString stringWithFormat:@"%@?c=User&&a=updateHeaderImg",requestURL]
           parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            
            NSData *imageData = UIImageJPEGRepresentation(self.headerImg.image, 1);
            
            if (imageData.length > 5000000) {
                imageData = UIImageJPEGRepresentation(self.headerImg.image, 0.1);
            }
            else if (imageData.length > 3000000) {
                imageData = UIImageJPEGRepresentation(self.headerImg.image, 0.3);
            }
            else if (imageData.length > 1000000) {
                imageData = UIImageJPEGRepresentation(self.headerImg.image, 0.5);
            }
            
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
            
            //上传的参数(上传图片，以文件流的格式)
            [formData appendPartWithFileData:imageData
                                        name:@"img"
                                    fileName:fileName
                                    mimeType:@"image/jpeg"];
            
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            //打印下上传进度
            NSLog(@"%@", uploadProgress);
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            //上传成功
            if ([responseObject[@"state"] isEqualToString:@"SUCCESS"]) {
                NSLog(@"上传图片成功");
                NSLog(@"%@", responseObject[@"data"]);
                [[NSUserDefaults standardUserDefaults]setObject:responseObject[@"data"] forKey:@"user"];
                //将左边控制器用户的头像更改
                [[NSNotificationCenter defaultCenter]postNotificationName:@"changeUserHeader" object:responseObject[@"data"][@"imgs"][0]];
            }
            else {
                NSLog(@"上传图片失败 %@", responseObject[@"data"]);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //上传失败
            NSLog(@"上传图片 失败 %@", error);
        }];
    }
}



- (void)tapOnAddressView {
    BPAddressViewController *addressVC = [[BPAddressViewController alloc]init];
    [self.navigationController pushViewController:addressVC animated:YES];
}

- (IBAction)femaleClick:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    _male.selected = !_female.isSelected;
}

- (IBAction)maleClick:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    _female.selected = !_male.isSelected;
}


@end
